const mysqlUtil = require('../util/mysqlUtil');
const superagent = require('superagent');

function _notice() {
    var date = new Date();

    if (date.getHours() < 8 || date.getHours() > 20) {
        return;
    }

    var sql = ` select p.code, p.name, p.leader_tels, group_concat(usp.description, '^') descriptions, count(1) c
                from t_ug_simple_package usp 
                left join t_ug_package_project upp on upp.package_id = usp.id
                left join t_ug_project p on p.id = upp.project_id
                where usp.is_publish=1 and (upp.is_finish_deploy=0 or upp.is_finish_deploy is null)
                group by p.name, p.leader_tels`;

    mysqlUtil.exec(sql, [], function(err, result) {
        for (var i = 0; i < result.length; i++) {
            var leader_telsArrs = result[i].leader_tels.split(';');
            var telsdes = '';
            for (var j = 0; j < leader_telsArrs.length; j++) {
                telsdes += '@' + leader_telsArrs[j] + ' ';
            }

            var descriptionsArr = result[i].descriptions.split('^');
            var content = telsdes + ' 【' + result[i].name + '】 当前有' + result[i].c + '个升级包还未升级，请及时部署验证，谢谢！';
            for (var j = 0; j < descriptionsArr.length; j++) {
                if (descriptionsArr[j] !== '') {
                    content += '\n\n' + descriptionsArr[j];
                }
            }

            superagent.post('https://oapi.dingtalk.com/robot/send?access_token=03799d4f8f43e24808c891115377090744878180bb4bf5388d7730a632312893').send({
                "msgtype": "text",
                "text": {
                    "content": content
                },
                "at": {
                    "atMobiles": leader_telsArrs,
                    "isAtAll": false
                }
            }).end(function(err, res) {
                console.log('ugNotice');
            });

        }
    });
}

/**
 * 定时通知实施人员部署升级包
 */
module.exports = function() {
    _notice();

    setInterval(function() {
        _notice();
    }, 1000 * 60 * 60 * 3);
};